package repository

import (
	"fmt"
	"gluenet/modules/manager/server/adapter/repository/mysql"
	"gluenet/modules/manager/server/domain/dependency"
	"gluenet/modules/manager/server/domain/entity"
	"gluenet/modules/manager/server/domain/po"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
	"time"
)

func init() {
	prepare.RegisterRepo(func() {
		repo := NewUserRepo()
		prepare.InjectDependency(func() dependency.UserRepo {
			return repo
		})
	})
}

func NewUserRepo() *User {
	r := &User{}
	return r
}

type User struct {
}

func (r *User) Get(UserID string) (*entity.Auth, error) {
	var obj []entity.Auth
	if err := mysql.DB.Where(map[string]interface{}{
		"id": UserID,
	}).Find(&obj); err != nil {
		return nil, err
	}

	//fmt.Printf("%v %v", len(obj), obj)

	if len(obj) > 1 {
		return nil, fmt.Errorf("much primary keys in sql")
	}

	if len(obj) == 0 {
		return nil, infra.DataNotFind
	}

	return &obj[0], nil
}

func (r *User) FindByName(proname string) (obj *entity.Auth, e error) {
	//TODO implement me
	panic("implement me")
}

func (r *User) FindByToken(token string) (*entity.Auth, error) {
	var obj []po.User
	if err := mysql.DB.SQL(`select * from user where token = ?`, token).Find(&obj); err != nil {

	}
	if len(obj) == 0 {
		return nil, fmt.Errorf("can't find data")
	}
	return &entity.Auth{
		User: obj[0],
	}, nil
}

func (r *User) Save(obj *entity.Auth) error {
	if _, err := mysql.DB.InsertOne(obj); err != nil {
		return err
	}
	return nil
}

func (r *User) Update(obj *entity.Auth) error {
	if _, err := mysql.DB.Update(obj); err != nil {
		return err
	}
	return nil
}

func (r *User) New(name string) (*entity.Auth, error) {
	t := time.Now()
	user := entity.Auth{}
	user.ID = infra.NewID()
	user.Name = name
	user.Create = t
	user.Update = t

	if _, err := mysql.DB.InsertOne(user.User); err != nil {
		return nil, err
	}
	return &user, nil
}
